import * as assert from 'assert';
import * as vscode from 'vscode';
import { fuchsia } from '../node_modules/@types/color-name';
import { prependListener } from 'cluster';
const fs = require('fs')
const path = require('path')
function getDeclareInfo(filePath: string) {
    let lines: string[] = fs.readFileSync(filePath, 'utf-8').split("\n")
    let className = ""
    for (let line of lines) {
        if (line.trim().indexOf("export class") == 0) {
            let wordList = line.split(" ").map((str) => { return str.trim() }).filter((str) => { return !!str })
            className = wordList[2]
            break
        }
    }
    return {
        className,
    }
}

function isUpper(char: string) {
    // A - Z 对应的 Unicode 编码是 65 - 90
    if (!char) {
        return false
    }
    let code = char.charCodeAt(0)
    if (code >= 65 && code <= 90) {
        return true
    }
}

function nameTrans(baseName: string) {
    // 驼峰法转为下划线分割
    let str = ''
    for (let i = 0; i < baseName.length; i++) {
        //是大写不是第一个字符而且前一个字符不是大写，则补充下划线
        if (isUpper(baseName[i]) && baseName[i - 1] && !isUpper(baseName[i - 1])) {
            str += "_"
        }
        str += baseName[i]
    }
    return str.toUpperCase()
}

function writeDeclareInfo(tgtFile: string, className: string, note: string) {
    let lines: string[] = fs.readFileSync(tgtFile, 'utf-8').split("\n")
    let baseName = nameTrans(className.replace("Mediator", ""))
    let openMsg = "OPEN_" + baseName
    let closeMsg = "CLOSE_" + baseName
    let hasAddOpen = lines.findIndex((vue) => {
        return vue.trim().indexOf('public static ' + openMsg) == 0
    }) > 0
    let hasAddClose = lines.findIndex((vue) => {
        return vue.trim().indexOf('public static ' + closeMsg) == 0
    }) > 0
    if (!hasAddOpen && !hasAddClose) {
        // let note = "注释"
        let addLines = [
            `	// ${note}`,
            `	public static ${openMsg}: string = "MainNotify_${openMsg}"`,
            `	public static ${closeMsg}: string = "MainNotify_${closeMsg}"`,
            ''
        ]
        let lineCount = lines.length
        for (let i = lineCount - 1; i >= 0; i--) {
            let line = lines[i]
            if (line.trim().indexOf("}") == 0) {
                lines.splice(i, 0, ...addLines)
                break
            }
        }
        let newStr = lines.reduce((pre, cur, curIdx) => {
            if (curIdx != 0) {
                pre += "\n"
            }
            pre += cur
            return pre
        }, '')
        fs.writeFileSync(tgtFile, newStr)
        vscode.window.showInformationMessage("add declare success")
    } else {
        vscode.window.showErrorMessage("already had:" + (hasAddClose ? openMsg + ";" : ";") + (hasAddClose ? closeMsg : ""))
    }
}

export function addReclare(filePath: string) {
    if (!filePath) {
        vscode.window.showErrorMessage("src file isTemp")
        return
    }
    let tgtFile = ""
    let splitSign = "SmartpikachuGame/src/"
    if (filePath.indexOf(splitSign) > 0) {
        filePath = filePath.replace("file:///", '')
        tgtFile = path.join(filePath.split(splitSign)[0], splitSign, 'core/controller/MainNotify.ts')
    }
    if (!tgtFile) {
        vscode.window.showErrorMessage("tgt file dir isTemp")
        return
    }
    if (fs.existsSync(tgtFile)) {
        let declareInfo = getDeclareInfo(filePath)
        if (declareInfo && declareInfo.className) {
            vscode.window.showInputBox({ placeHolder: "请输入注释" }).then((vue) => {
                if (vue) {
                    writeDeclareInfo(tgtFile, declareInfo.className, vue)
                }
            })
            // writeDeclareInfo(tgtFile, declareInfo.className)
        } else {
            vscode.window.showErrorMessage("not find declareInfo")
        }
    } else {
        vscode.window.showErrorMessage("tgt file isTemp")
    }
}

export function replaceMsg(filePath: string) {
    let declareInfo = getDeclareInfo(filePath)
    if (declareInfo && declareInfo.className) {
        let baseName = nameTrans(declareInfo.className.replace("Mediator", ""))
        let openMsg = "OPEN_" + baseName
        let closeMsg = "CLOSE_" + baseName
        let fileStr: string = fs.readFileSync(filePath, 'utf-8')
        fileStr = fileStr.replace(/this.openMessage = .*/, `this.openMessage = MainNotify.${openMsg}`)
        fileStr = fileStr.replace(/this.closeMessage = .*/, `this.closeMessage = MainNotify.${closeMsg}`)
        fs.writeFileSync(filePath, fileStr)
        vscode.window.showInformationMessage("add declare success")
    }
}